package vn.ikame.android.plugin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

import vn.ikame.android.boojtran.truyenbua.R;
import vn.ikame.android.boojtran.truyenbua.SuperActivity;
import vn.ikame.android.boojtran.truyenbua.object.GA;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class ChatActivity extends BaseActivity implements OnClickListener {
	/** Called when the activity is first created. */

	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	public static final int ITEM_PER_PAGE = 20;

	private AlertDialog.Builder alert;
	private ProgressDialog mProgressDialog;
	ListView list;
	ListCommentAdapter arrayAdapter;
	int curPage = 1, numOfPage = 1;

	EditText content, mobile, nickName, page;
	Store store;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);
		store = new Store(this);

		// GA.trackGeneralView(SuperActivity.APP_NAME + "_goToChat");
		SuperActivity.generalTracker.trackPageView(SuperActivity.APP_NAME
				+ "_goToChat");
		SuperActivity.generalTracker.dispatch();
		GA.trackAppView(SuperActivity.APP_NAME + "_goToChat");

		((ImageButton) findViewById(R.id.bt_send)).setOnClickListener(this);
		((ImageButton) findViewById(R.id.bt_left)).setOnClickListener(this);
		((ImageButton) findViewById(R.id.bt_right)).setOnClickListener(this);

		content = (EditText) findViewById(R.id.text_content);
		mobile = (EditText) findViewById(R.id.text_sdt);
		nickName = (EditText) findViewById(R.id.text_nickname);
		page = (EditText) findViewById(R.id.page);

		mobile.setText(store.getMobile());
		nickName.setText(store.getUserName());

		if (Parser.isNetworkConnected(this)) {
			getComment(curPage);
		} else {
			alert = new AlertDialog.Builder(this);
			alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
			alert.setPositiveButton("Thử lại",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							getComment(curPage);
						}
					});
			alert.setNegativeButton("Thoát",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							ChatActivity.this.finish();
							System.gc();
							android.os.Process.killProcess(android.os.Process
									.myPid());
						}
					});

			alert.setCancelable(true);
			alert.show();
		}

		list = (ListView) findViewById(R.id.list_comment);
		list.setAdapter(arrayAdapter);
		// list.setSelection(a.size() - 1);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			finish();
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu_tangau, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.moregame:
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("market://search?q=ikame"));
			startActivity(intent);
			break;
		case R.id.rateapp:
			Intent intent1 = new Intent(Intent.ACTION_VIEW);
			intent1.setData(Uri.parse("market://details?id=" + APP_PACKAGE));
			startActivity(intent1);
			break;
		case R.id.refresh:
			if (Parser.isNetworkConnected(this)) {
				getComment(curPage);
			} else {
				alert = new AlertDialog.Builder(this);
				alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
				alert.setPositiveButton("Thử lại",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								getComment(curPage);
							}
						});
				alert.setNegativeButton("Thoát",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								ChatActivity.this.finish();
								System.gc();
								android.os.Process
										.killProcess(android.os.Process.myPid());
							}
						});

				alert.setCancelable(true);
				alert.show();
			}
			break;

		}
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.bt_send:
			if (content.getText().toString().trim().equals("")) {
				Toast.makeText(this, "Bạn phải nhập nội dung",
						Toast.LENGTH_SHORT).show();
			} else if (nickName.getText().toString().trim().length() < 3) {
				Toast.makeText(this, "Nick name phải có tối thiểu 3 kí tự",
						Toast.LENGTH_SHORT).show();
			} else {
				try {
					// new AsyncTask<Void, Void, Void>() {
					//
					// @Override
					// protected Void doInBackground(Void... params) {
					doSend();
					// return null;
					// }
					// }.execute();
				} catch (Exception e) {
					e.printStackTrace();
				}
				store.setMobile(mobile.getText().toString().trim());
				store.setUserName(nickName.getText().toString().trim());
			}
			break;
		case R.id.bt_left:
			if (curPage > 1) {
				curPage--;
				page.setText(curPage + "/" + numOfPage);
				getComment(curPage);
			}
			break;
		case R.id.bt_right:
			if (curPage < numOfPage) {
				curPage++;
				page.setText(curPage + "/" + numOfPage);
				getComment(curPage);
			}
			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}

	public void getComment(final int page) {
		try {
			// Tạo task kết nối với server
			new AsyncTask<Void, Void, String>() {
				@Override
				protected void onPreExecute() {
					// Hiển thị thông báo
					try {
						showDialog(DIALOG_DOWNLOAD_PROGRESS);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(Void... arg0) {
					try {

						Thread theard = new Thread() {
							@Override
							public void run() {
								try {

									int waited = 0;
									while (true && (waited < 10000)) {
										sleep(100);
										if (true) {
											waited += 100;
										}
									}

								} catch (Exception e) {
									// do nothing
								} finally {
									try {
										System.out
												.println("Không kết nối được đến server");
										dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
									} catch (Exception e) {
										// TODO: handle exception
									}
								}
							}
						};
						theard.start();

						Parser.cmList = Parser.getCommentList(DATA_LINK
								+ "services/appServer.php?index=comment&appid="
								+ APP_ID + "&start="
								+ ((page - 1) * ITEM_PER_PAGE) + "&count="
								+ ITEM_PER_PAGE);

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 2");
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 3");
					}
					return "";
				}

				// Hoàn thành truy vấn
				@Override
				protected void onPostExecute(String result) {

					try {
						arrayAdapter = new ListCommentAdapter(
								ChatActivity.this, R.layout.chatlistview,
								Parser.cmList);

						list = (ListView) ChatActivity.this
								.findViewById(R.id.list_comment);
						list.setAdapter(arrayAdapter);
						// list.setSelection(Parser.cmList.size() - 1);

						if (Comment.total % ITEM_PER_PAGE == 0) {
							numOfPage = Comment.total / ITEM_PER_PAGE;
						} else {
							numOfPage = Comment.total / ITEM_PER_PAGE + 1;
						}
						initView();
					} catch (Exception e) {
					}
					try {
						dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
					} catch (Exception ee) {
						// TODO: handle exception
					}
				}
			}.execute();
		} catch (Exception e) {
		}
	}

	public void initView() {
		page.setText(curPage + "/" + numOfPage);
		page.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					page.setText(curPage + "");
					page.setSelection(page.getText().toString().trim().length());
					showSoftKeyboard();
				} else {
					page.setText(curPage + "/" + numOfPage);
					hideSoftKeyboard();
				}
			}
		});

		page.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				try {
					if (!page.getText().toString().trim().equals("")) {
						curPage = Integer.parseInt(page.getText().toString()
								.trim());
						if (curPage > numOfPage) {
							curPage = numOfPage;
						} else if (curPage <= 0) {
							curPage = 1;
						}
						page.setText(curPage + "/" + numOfPage);
						page.clearFocus();
						getComment(curPage);
					}

				} catch (Exception e) {
				}
				return false;
			}
		});
	}

	public class CustomListView extends LinearLayout {
		public TextView nickName;
		public TextView content;

		public CustomListView(Context context) {
			super(context);

			// Sử dụng LayoutInflater để gán giao diện trong list.xml cho class
			// này
			LayoutInflater li = (LayoutInflater) this.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			li.inflate(R.layout.chatlistview, this, true);

			// Lấy v�? các View qua Id
			nickName = (TextView) findViewById(R.id.nickname);
			content = (TextView) findViewById(R.id.content);
		}
	}

	public class ListCommentAdapter extends ArrayAdapter<Comment> {
		ArrayList<Comment> array;
		int resource;
		Context context;

		public ListCommentAdapter(Context context, int textViewResourceId,
				ArrayList<Comment> objects) {
			super(context, textViewResourceId, objects);
			this.context = context;
			resource = textViewResourceId;
			array = objects;
		}

		// <font color="red">//Phương thức xác định View mà Adapter hiển thị, ở
		// đây chính là CustomViewGroup
		// Bắt buộc phải Override khi kế thừa từ ArrayAdapter</font>
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;

			if (view == null) {
				view = new CustomListView(getContext());
			}

			final Comment cm = array.get(position);

			if (cm != null) {
				TextView content = ((CustomListView) view).content;
				content.setText(" " + cm.getContent());

				String text;

				if (cm.getNickName().equalsIgnoreCase("admin")) {
					text = "<font color=#ac0b0f><b>" + cm.getNickName()
							+ ": </b></font> <font color=#ffffff>"
							+ cm.getContent() + "</font>";
				} else {
					if (position % 2 == 1) {
						text = "<font color=#3e2a21><b>" + cm.getNickName()
								+ ": </b></font> <font color=#ffffff>"
								+ cm.getContent() + "</font>";
					} else {
						text = "<font color=#3464bb><b>" + cm.getNickName()
								+ ": </b></font> <font color=#ffffff>"
								+ cm.getContent() + "</font>";
					}
				}
				content.setText(Html.fromHtml(text));
			}
			return view;
		}

		@Override
		public boolean isEnabled(int position) {
			return false;
		}
	}

	public void doSend() {
		try {
			String output = nickName.getText().toString().trim();
			String userName = nickName.getText().toString().trim()
					.toLowerCase();
			if (userName.equalsIgnoreCase("admin")) {
				userName = userName + " giả mạo";
				output = userName;
			}

			// Construct data
			String data = URLEncoder.encode("username", "UTF-8") + "="
					+ URLEncoder.encode(checkString(output), "UTF-8");
			data += "&"
					+ URLEncoder.encode("comment", "UTF-8")
					+ "="
					+ URLEncoder.encode(checkString(content.getText()
							.toString()), "UTF-8");
			data += "&"
					+ URLEncoder.encode("email", "UTF-8")
					+ "="
					+ URLEncoder.encode(UserEmailFetcher.getEmail(this),
							"UTF-8");
			data += "&"
					+ URLEncoder.encode("description", "UTF-8")
					+ "="
					+ URLEncoder.encode(android.os.Build.MODEL + "\n"
							+ mobile.getText().toString(), "UTF-8");
			// Send data
			String urlStr = DATA_LINK
					+ "services/appServer.php?index=comment&appid=" + APP_ID;
			URL url = new URL(urlStr);
			System.out.println("VKL: url = " + urlStr);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(
					conn.getOutputStream());
			wr.write(data);
			wr.flush();

			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			// String line;
			// while ((line = rd.readLine()) != null) {
			// // Process line...
			// }
			wr.close();
			rd.close();
			content.setText("");
			curPage = 1;
			page.setText(curPage + "/" + numOfPage);
			getComment(curPage);
		} catch (Exception e) {
			Toast.makeText(
					this,
					"Có lỗi xảy ra. Vui lòng kiểm tra lại kết nối mạng và thử lại",
					Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			try {
				dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	private void hideSoftKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
	}

	private void showSoftKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		imm.showSoftInput(getCurrentFocus(), 0);
	}

	public static String checkString(String input) {
		char[] tmp = input.toLowerCase().toCharArray();
		for (int i = 0; i < tmp.length; i++) {
			switch (tmp[i]) {
			case '<':
				tmp[i] = '(';
				break;
			case '>':
				tmp[i] = ')';
				break;
			}
		}
		return String.valueOf(tmp);
	}
}